import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {Router, ActivatedRoute} from "@angular/router";
import {TableUtil} from "../../../util/table-util";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../util/response-util";
import {PageSubject} from "../../../util/page-subject";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {API, MsgConstants} from "../../../constants/constants";
import {SitesService} from "./sites.service";
import {MsgResult} from "../../../models/msg-result";
import {Categorys} from "../categorys/categorys";

declare var $;

@Component({
  selector: 'app-sites',
  templateUrl: 'sites.component.html'
})
export class SitesComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  siteId : string;

  siteCode : string;

  categorys :Categorys;

  table;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private sitesService: SitesService,
    private responseUtil:ResponseUtil,
    private pageSubject: PageSubject
  ) { }

  proxy = {
    "siteAdd": () => this.siteAdd(),
    "siteUpdate": () => this.siteUpdate(),
    "siteDelete": () => this.siteDelete(),
    "assignSite": () => this.assignSite(),
  }

  ngOnInit() {
    this.pushPage();
    this.loadSite();
    this.initSiteCategory();
  }

  //操作函数代理
  ngAfterViewInit() {
    this.operation.proxy = this.proxy;
  }

  /**
   *  生成面包屑
   */
  private pushPage() {
    let path = new Path("设备监测", null);
    this.pageSubject.pushPage("站点管理", "查询", path);
  }

  /**
   * 初始化站点类型
   */
  initSiteCategory(){
    this.sitesService.getSiteCategoryInfos().subscribe(
      result =>this.responseUtil.success(result ,this.processSiteCategoryResult),
      error => this.responseUtil.error(error)
    );
  }

  private processSiteCategoryResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.categorys = result.data;

    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //搜索
  search(){
    this.table.bootstrapTable('refresh');
  }

  /**
   * 站点查询
   */
  loadSite(){
    this.table = this.tableUtil.load("one_table_site",{
      columns:[
        { checkbox: true },
        { field: "id", title:'ID',align:'left',visible:false,switchable:false},
        { field: "siteCode", title:'站点编码',align:'left',visible:false,switchable:false},
        { field: "siteName", title:'站点名称',align:'left'},
        { field: "siteTypeName", title:'站点类型',align:'left'},
        { field: "regionName",title:'行政区划' ,align:'left'},
        { field: "address",title:'站点位置' ,align:'left'},
        // { field: "studySiteName" ,title:'学习标准站点',align:'left',width: 70},
        // { field: "valleyCode",title:'河流代码' ,align:'left',width: 150 },
        // { field: "examineRegionCode",title:'考核城市代码' ,align:'left',width: 150 },
        { field: "isThied",title:'第三方' ,align:'left',formatter : this.yesOrNoFormat},
        { field: "isMove",title:'移动设备' ,align:'left',formatter : this.yesOrNoFormat},
        { field: "isUse",title:'启用' ,align:'left',formatter : this.yesOrNoFormat},
        { field: "createDate",title:'创建时间' ,align:'left' ,sortName:"CREATEDATE",sortable:true,visible: false}
      ],
      idField:"id",
      sidePagination:'server',
      pagination:true,
      pageNumber:1,
      pageSize:15,
      pageList: [10,15, 50],
      paginationPreText:"上一页",
      paginationNextText:"下一页",
      paginationLoop:false,//是否开启循环分页
      singleSelect: true,//多选
      clickToSelect:true,//点击选中
      toolbar:"#one_operation_sites",
      url:API.sitePageListV2,
      method:'post',
      //传递附加参数
      queryParams:(params) => {
        params.siteName = $("#siteName").val();
        params.siteTypeCode = $("#monitor_add_siteTypeCode").val();
        return params;
      },
      //返回数据处理器
      responseHandler:(result)=>{
        return this.responseUtil.bsPageHandler(result,(result)=>{
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
          });
        });
      },
      height:700,//table高度
      sortable:true,
      order:'asc',
      sortName:'CREATEDATE',
      showColumns:true,//显示自定义显示列按钮
      showRefresh:true,//显示刷新按钮
      minimumCountColumns:3,//最少保留显示的列数量
      showToggle:true,//显示视图切换按钮
      showPaginationSwitch:true,//显示是否分页切换按钮
      showExport: true,       //是否显示导出按钮
      exportDataType: 'all', //导出类型
      buttonsAlign: "right",  //按钮位置
      exportTypes: ['excel'],  //导出文件类型
      exportOptions: {
        ignoreColumn: [0],  //根据索引忽[0,1,2]略某一列的导出数据
        fileName: '站点数据报表',  //保存文件名称设置
        worksheetName: 'sheet1',  //表格工作区名称
        tableName: '设备数据报表',
        excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],

      },
      classes:"table table-hover",
      striped:true,//隔行变色
      mobileResponsive:true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value,row,index){
    if(value == '0'){
      return "否";
    }
    if(value == '1'){
      return "是";
    }
  }

  /**
   * 删除站点操作
   */
  private siteDelete() {
    let rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo("请选择一条数据!");
    }
    this.siteId = this.tableUtil.getId(rows[0]);
    this.siteCode = this.tableUtil.getCloumn(rows[0], "siteCode");

    if (!this.siteId || !this.siteCode) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }

  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
    //调用后端接口
    if (!!this.siteId && !!this.siteCode) {
      this.sitesService.deleteSite(this.siteId, this.siteCode).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
    }
  }

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 站点添加
   */
  private siteAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   * 站点修改
   */
  private siteUpdate() {
    let rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo("请选择一条数据");
    }
    this.siteId = this.tableUtil.getId(rows[0]);
    if (!!this.siteId) {
      this.router.navigate(['update', {siteId: this.siteId}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo("请选择一条数据");
    }
  }

  /**
   * 为站点分配设备
   */
  private assignSite() {
    let rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo("请选择一条数据!");
    }
    this.siteId = this.tableUtil.getCloumn(rows[0], "id");
    if (!!this.siteId) {
      this.router.navigate(['assign', {id: this.siteId}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo("请选择一条数据!");
    }
  }

}
